package io.renren.service.business;

import io.renren.common.exception.RRException;
import io.renren.entity.UserEntity;
import io.renren.form.LoginForm;
import io.renren.form.RegisterForm;
import io.renren.service.SysUserService;
import io.renren.service.TokenService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author winson
 * @CREATE 20 16:25
 */
@Service("loginBusinessService")
public class LoginBusinessService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private TokenService tokenService;


    public String register( RegisterForm registerForm ){

        // 校验是否存在此用户名
        UserEntity userEntity = sysUserService.queryByUsername( registerForm.getUsername() );
        if( userEntity != null ){
            throw new RRException("此用户名已注册");
        }

        userEntity = new UserEntity();
        userEntity.setUsername( registerForm.getUsername() );
        userEntity.setHeadUrl( registerForm.getHeadUrl() );
        userEntity.setRegType( registerForm.getRegType() );
        userEntity.setType( 0 );
        userEntity.setPassword( DigestUtils.sha256Hex( registerForm.getPassword()) );
        userEntity.setNickName( registerForm.getNickName() );

        userEntity.setRegTime( new Date() );
        userEntity.setIsDeleted( 0 );
        userEntity.setIsLock( 0 );
        userEntity.setLoginTime( new Date() );

        // 保存注册
        sysUserService.insert( userEntity );

        // 自动登录
        LoginForm loginForm = new LoginForm();
        loginForm.setUsername( registerForm.getUsername() );
        loginForm.setMobile( registerForm.getMobile() );
        loginForm.setPassword( registerForm.getPassword() );

        // 返回token
        return tokenService.createToken( userEntity.getUserId() ).getToken();

    }

}
